package com.kuaiying.kuai.ying.controller.shop;


import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;
import com.kuaiying.kuai.ying.model.leaflet.LeafletModel;
import com.kuaiying.kuai.ying.model.print_file.PrintfileModel;
import com.kuaiying.kuai.ying.model.task_id.TaskidModel;
import com.kuaiying.kuai.ying.model.user.UserModel;
import com.kuaiying.kuai.ying.model.print_shop.PrintshopModel;
import com.kuaiying.kuai.ying.model.school.SchoolModel;
import com.kuaiying.kuai.ying.model.shop.ShopModel;
import com.kuaiying.kuai.ying.validator.HomeValidator;
import com.kuaiying.kuai.ying.validator.LoginValidator;
import com.kuaiying.kuai.ying.validator.RegistValidator;
import com.kuaiying.kuai.ying.validator.UploadValidator;

import java.text.SimpleDateFormat; 
import java.util.Date;

public class shopController extends Controller{

	public void index(){
		String uName = getSessionAttr("shop_phonenumber");
		if( uName != null ){
			redirect("/shop/print");
			return;
		}
		render("login.html");
	}
	
	public void login(){
		String uName = getSessionAttr("shop_phonenumber");
		if( uName != null ){
			System.out.println( "has shop_phonenumber :" + uName );
			redirect("/shop/print");
			return;
		}
		render("login.html");
	}
	
	@Before( LoginValidator.class )
	public void loginPost(){
		
		String phonenumber = getPara("phonenumber");
    	String pwd = getPara("password");
    	ShopModel shop = ShopModel.me.getUserByNameAndPwd(phonenumber, pwd);
    	
    	if (shop != null){
            String bbsID = phonenumber + pwd;
            setCookie("bbsID", bbsID, 3600*24*30);
            setSessionAttr("shop_phonenumber", phonenumber);
            setSessionAttr("shopID", shop.get("shop_id"));
            Integer shop_id = shop.get("shop_id");
            //修改用户登录时间
            ShopModel.me.upadteshop_lastlogintime(shop_id);
            redirect("/shop/print");
        }else{
            setAttr("loginError", "用户名或密码错误");
            render("login.html");
        }
	}

	public void unpdataPost(){
		Integer user_id = getSessionAttr("shopID");
		ShopModel shopmodel = ShopModel.me.findById(user_id);
		String mobile = getPara("phonenum");
		String userName = getPara("truename");
		String email = getPara("email");
		String major = getPara("major");
		String password = getPara("password");
		String grade = getPara("grade");
		shopmodel.set("email", email);
		if (password != null){
			shopmodel.set("password", password);
		}
		shopmodel.update();
		//System.out.println( PrintshopModel.me.upadteUser(user_id,userName,email,grade,major) );
		redirect("/shop/info");
	}
	
	@Before( HomeValidator.class )
	public void home(){
		render("home.html");
	}
	
	public void print(){
		List<SchoolModel> schools = SchoolModel.me.getSchool();
		setAttr("schools", schools);
		render("print.html");
	}
	
	public void billing(){
		Integer shop_id = getSessionAttr("shopID");
		if( shop_id != null ){
			ShopModel shopModel = ShopModel.me.findById(shop_id);
			setAttr("shopModel", shopModel);
			
			Integer pageNumber = 1;
			Integer pagevalue = 10;
			try{
				pageNumber = Integer.valueOf(getPara("page"));
			}
			catch (Exception e){
				pageNumber = 1;
			}

			setAttr("nav_url", "/shop/billing");
	        List<LeafletModel> list = LeafletModel.me.getAllLeaftel_shop(shop_id);
	        Integer totlenum = list.size();	//分页测试
	        Integer totel_page = 1;
	        if( totlenum%pagevalue == 0 ){
	        	totel_page = (totlenum-totlenum%pagevalue)/pagevalue;
	        }else{
	        	totel_page = (totlenum-totlenum%pagevalue)/pagevalue+1;
	        }
			List<LeafletModel> list_page = LeafletModel.me.getAllLeaftel_shopage(shop_id,pageNumber);
	        setAttr("leafletList", list_page);
	        setAttr("pageNumber", pageNumber);
	        setAttr("totalPage", totel_page);
	        setAttr("totalRow", totlenum);
	        render("billing.html");
		}
	}
	
	public void order(){
		List<SchoolModel> schools = SchoolModel.me.getSchool();
		/*
		Collections.sort(schools,new Comparator(){
		     public int compare(Object o1, Object o2)
		     {

		    	 SchoolModel sdto1= (SchoolModel )o1;

		    	 SchoolModel sdto2= (SchoolModel )o2;

		         return sdto1.me.getInt("school_id").compareTo(sdto2.me.getInt("school_id"));

		     }
		});
		*/
		//为分页准备
		Integer pageNumber = 1;
		Integer pagevalue = 10;
		try{
			pageNumber = Integer.valueOf(getPara("page"));
		}
		catch (Exception e){
			pageNumber = 1;
		}
		setAttr("schools", schools);
		setAttr("nav_url", "/shop/order");
		Integer shop_id = getSessionAttr("shopID");
        List<LeafletModel> list = LeafletModel.me.getAllLeaftel_shop(shop_id);
        Integer totlenum = list.size();	//分页测试
        Integer totel_page = 1;
        if( totlenum%pagevalue == 0 ){
        	totel_page = (totlenum-totlenum%pagevalue)/pagevalue;
        }else{
        	totel_page = (totlenum-totlenum%pagevalue)/pagevalue+1;
        }
		List<LeafletModel> list_page = LeafletModel.me.getAllLeaftel_shopage(shop_id,pageNumber);
        setAttr("leafletList", list_page);
        setAttr("pageNumber", pageNumber);
        setAttr("totalPage", totel_page);
        setAttr("totalRow", totlenum);
        System.out.println( "123321123321123");
		render("order.html");
	}
	
	public void info(){
		Integer user_id = getSessionAttr("shopID");
		if( user_id != null ){
			ShopModel userModel = ShopModel.me.findById(user_id);
			setAttr("userModel", userModel);
			System.out.println( userModel.getStr("email"));
		    render("info.html");
		    return;
		}
	}
	
	public void quit(){
		removeSessionAttr("shop_phonenumber");
		removeSessionAttr("shopID");
		removeSessionAttr("money_enough_flag");
		removeCookie("bbsID");
		render("login.html");
	}
	
	public void upload(){
		Integer shop_id = getSessionAttr("shopID");

		
		String now_time = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format( new Date());
		System.out.println( "test_shop_leaflet\\"+Integer.toString(shop_id)+ "\\" + now_time+"\\" );
		UploadFile file = getFile("UpLoadFile","test_shop_leaflet123/"+Integer.toString(shop_id)+ "/" + now_time+"/",1000000);
		
		//添加数据库,添加文件
		Integer school_id = Integer.valueOf(getPara("school"));
		Integer good_num = Integer.valueOf(getPara("gold_num"));
		Integer remainder_money = Integer.valueOf(getPara("gold_num"));
		ShopModel shopModel = ShopModel.me.findById(shop_id);
        if(shopModel.getInt("pend_gold")-good_num < 0){
        	setSessionAttr("money_enough_flag", 1);
			redirect("/shop/print");
			return;
        }
        
		String filename = file.getSaveDirectory() + file.getFileName();
		LeafletModel.me.updateleafletfile(shop_id,file.getFileName(),filename,now_time,good_num,school_id,remainder_money);
		
		//shop修改金额
		System.out.println( shopModel.getInt("used_gold"));
		System.out.println( shop_id);
		shopModel.set("used_gold", shopModel.getInt("used_gold")+good_num);
		shopModel.set("pend_gold", shopModel.getInt("pend_gold")-good_num);
		shopModel.update();
		
//		LeafletModel savefileid = ShopModel.me.getFileid(user_id,file.getFileName(),file.getSaveDirectory() + file.getFileName());
		//添加数据库，添加任务
		redirect("/shop/order");
	}
	

	public void download() {
		LeafletModel leaflet = LeafletModel.me.findById(getParaToInt());
		String path = (String) leaflet.get("path");
		System.out.println( path );
	    renderFile(new File(path));
	    //render("upload.html");
	}
	
	  public void delete() {
	        // 获取表单域名为studentID的值
	        // Student.dao.deleteById(getPara("studentID"));
	        // 获取url请求中第一个值
		  LeafletModel leaflet = LeafletModel.me.findById(getParaToInt());
		  System.out.println( leaflet.getInt("leaflet_id") );
		  System.out.println( getParaToInt() );
		  leaflet.set("finish_flag", 1);
		  leaflet.update();
		  
		  //删除的传单金额返还给shop
		  Integer use_gold = leaflet.getInt("use_gold");
		  Integer gold_num = leaflet.getInt("gold_num");
		  Integer pend_gold = gold_num - use_gold;
		  
		  Integer shop_id = getSessionAttr("shopID");
		  ShopModel shopModel = ShopModel.me.findById(shop_id);
		  shopModel.set("used_gold", shopModel.getInt("used_gold")-pend_gold);
		  shopModel.set("pend_gold", shopModel.getInt("pend_gold")+pend_gold);
		  shopModel.update();
		  redirect("/shop/order");
	    }
}
